package cz.fit.vutbr.pis2012.augeaswh.control.ekonom.subscriber;

import java.io.Serializable;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import cz.fit.vutbr.pis2012.augeaswh.managers.SubscriberManager;
import cz.fit.vutbr.pis2012.augeaswh.persistence.BankAccount;
import cz.fit.vutbr.pis2012.augeaswh.persistence.Subscriber;

@ManagedBean
@SessionScoped
public class SubscriberEditorBean implements Serializable {
	@EJB
	private SubscriberManager sm;
	
	private static final long serialVersionUID = -6000365533104340973L;
	private Subscriber subscriber;
	private String name;
	private String ico;
	private String dic;
	private String accountNumber;
	private String bankName;
	private String iban;
	

	public SubscriberEditorBean() {
		setSubscriber(null);
	}
	
	public Subscriber getSubscriber() {
		return subscriber;
	}

	public void setSubscriber(Subscriber subscriber) {
		this.subscriber = subscriber;
		name=ico=dic=accountNumber=bankName=iban="";
		if(this.subscriber!=null) {
			this.name=subscriber.getName();
			this.ico=subscriber.getIco();
			this.dic=subscriber.getDic();
			if(subscriber.getBankAccount()!=null) {
				this.accountNumber=subscriber.getBankAccount().getAccountNumber();
				this.bankName=subscriber.getBankAccount().getBankName();
				this.iban=subscriber.getBankAccount().getIban();
			}
		}
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getIco() {
		return ico;
	}

	public void setIco(String ico) {
		this.ico = ico;
	}

	public String getDic() {
		return dic;
	}

	public void setDic(String dic) {
		this.dic = dic;
	}

	public String getAccountNumber() {
		return accountNumber;
	}

	public void setAccountNumber(String accountNumber) {
		this.accountNumber = accountNumber;
	}

	public String getBankName() {
		return bankName;
	}

	public void setBankName(String bankName) {
		this.bankName = bankName;
	}

	public String getIban() {
		return iban;
	}

	public void setIban(String iban) {
		this.iban = iban;
	}
	
	public String submit() {
		
		if(subscriber==null) {
			this.subscriber=new Subscriber();
		}
		this.subscriber.setName(name);
		this.subscriber.setIco(ico);
		this.subscriber.setDic(dic);
		if(this.subscriber.getBankAccount()==null)
			this.subscriber.setBankAccount(new BankAccount());
		BankAccount ba=this.subscriber.getBankAccount();
		ba.setAccountNumber(accountNumber);
		ba.setBankName(bankName);
		ba.setIban(iban);
		sm.save(subscriber);
		setSubscriber(null);
		return "back";
	}
	
	public String getTitle() {
		if(this.subscriber==null) {
			return "New supplier";
		}
		else {
			return "Edited subscriber \""+this.subscriber.getName()+"\"";
		}			
	}
}
